package cn.xyinping.order.service.impl;

import cn.xyinping.basic.exception.MyException;
import cn.xyinping.basic.service.impl.BasicServiceImpl;
import cn.xyinping.basic.util.LoginContextUtil;
import cn.xyinping.order.domain.OrderAddress;
import cn.xyinping.order.domain.OrderPet;
import cn.xyinping.order.domain.OrderPetDetail;
import cn.xyinping.order.dto.OrderDto;
import cn.xyinping.order.service.IOrderAddressService;
import cn.xyinping.order.service.IOrderPetDetailService;
import cn.xyinping.order.service.IOrderPetService;
import cn.xyinping.pay.domain.PayBill;
import cn.xyinping.pay.service.IPayBillService;
import cn.xyinping.pet.domain.Pet;
import cn.xyinping.pet.service.IPetService;
import cn.xyinping.user.domain.Logininfo;
import cn.xyinping.user.domain.UserAddress;
import cn.xyinping.user.mapper.UserAddressMapper;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

/**
 * @author 27266
 * @desrciption 宠物订单
 * @date 2021/11/7
 */
@Service
@Transactional
public class OrderPetServiceImpl extends BasicServiceImpl<OrderPet> implements IOrderPetService {
    @Autowired
    private IPetService petService;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private IOrderPetDetailService orderPetDetailService;
    @Autowired
    private IOrderAddressService orderAddressService;
    @Autowired
    private IPayBillService payBillService;
    @Override
    public String saveOrder(OrderDto dto) {
        Long addressId = dto.getAddressId();
        Integer payType = dto.getPayType();
        Long petId = dto.getPetId();
        // 1. 非空校验
        if (StringUtils.isEmpty(addressId)
                || StringUtils.isEmpty(payType)
                || StringUtils.isEmpty(petId)) {
            throw new MyException("参数不能为空");
        }

        // 2. 通过id查询到宠物信息，判断宠物上架
        // 先上锁在查询，如果库存为零，线程二就进不来
        Pet pet = null;
        synchronized (this) {
            pet = petService.selectOnLineById(petId);
            if (null == pet) {
                throw new MyException("该宠物为上架");
            }
            // 下单时减库存,防止超卖，当库存为0时就报异常
            // 防止多线程所以要上锁

            if (pet.getStore_number() == null || pet.getStore_number().intValue() == 0) {
                throw new MyException("库存不足");
            }
            pet.setStore_number(pet.getStore_number() - 1);
            petService.update(pet);
        }
        // 3. 查询用户地址
        UserAddress address = userAddressMapper.loadById(addressId);
        if (null == address) {
            throw new MyException("地址不能为空");
        }
        // 4.创建订单号，计算支付超市时间，保存订单数据
        String all = UUID.randomUUID().toString().replaceAll("-", "");
        Date date = new Date();
        // 使用lang包加时间做支付超时保存订单明细
        Date date1 = DateUtils.addMinutes(date, 30);
        // 保存订单
        OrderPet orderPet = new OrderPet();
        orderPet.setDigest("购买：" + pet.getName() + "下单");
        orderPet.setCreateTime(date);
        // 支付超时时间
        orderPet.setPayExpireTime(date1);
        // 订单号
        orderPet.setOrderSn(all);
        orderPet.setPayType(payType);
        // 支付状态:待支付
        orderPet.setState(OrderPet.STATE_WAIT_PAY);
        // 总数量
        orderPet.setTotalCount(1);
        // 金额+邮费
        orderPet.setTotalPrice(pet.getSaleprice().add(new BigDecimal("10")));
        // 获取登录用户
        Logininfo logininfo = LoginContextUtil.getLoginContext();
        if (logininfo == null) {
            throw new MyException("请登录");
        }
        orderPet.setUserId(logininfo.getId());
        super.add(orderPet);
        // 5. 保存订单明细
        OrderPetDetail detail = new OrderPetDetail();
        detail.setCount(1);
        detail.setCreatetime(date);
        //宠物名
        detail.setName(pet.getName());
        //订单
        detail.setOrderId(orderPet.getId());
        detail.setOrderSn(all);
        detail.setPetId(pet.getId());
        //价格
        detail.setPrice(pet.getSaleprice());
        //图片
        detail.setResources(pet.getResources());
        //店铺
        detail.setShopId(pet.getShop().getId());
        detail.setShopName(pet.getShop().getName());
        // 保存
        orderPetDetailService.add(detail);
        // 6. 保存订单地址
        OrderAddress orderAddress = new OrderAddress();
        // 属性拷贝
        BeanUtils.copyProperties(address, orderAddress);
        orderAddress.setOrderId(orderPet.getId());
        orderAddress.setOrderSn(all);
        orderAddress.setCreateTime(date);
        // 保存地址
        orderAddressService.add(orderAddress);

        // 7. 保存支付单
        payBillService.save(
                orderPet.getId(),
                PayBill.BUSINESS_TYPE_PET,
                "宠物购买" + pet.getName() + "支付" + orderPet.getTotalPrice(),
                orderPet.getTotalPrice(), //总价格
                dto.getPayType(),//支付方式用户选的
                pet.getShop().getId(),//店铺
                pet.getShop().getName(),
                orderPet.getOrderSn() //单号
        );
        // 返回订单号
        return orderPet.getOrderSn();
    }
}
